import { handleAccount } from '@/services/api';
import { queryUsersList, queryUserinfo, addUser } from '@/services/user';
import { message } from 'antd';
import router from 'umi/router';

export default {
  namespace: 'users',

  state: {
    userMap: {
      list: [],
      pagination: {},
    },
    userInfo: {},
  },

  effects: {
    *fetchUserMap({ payload }, { call, put }) {
      const response = yield call(queryUsersList, payload);
      console.log(response);
      yield put({
        type: 'save',
        payload: {
          list: response.data.data,
          pagination: {
            total: response.data.total,
            pageSize: 10,
            current: parseInt(response.data.currentPage, 10) || 1,
          },
        },
      });
    },
    *fetchUserInfo({ payload }, { call, put }) {
      const response = yield call(queryUserinfo, payload);
      console.log(response);
      yield put({
        type: 'saveUserinfo',
        payload: response.data,
      });
    },
    *addUser({ payload }, { call }) {
      const response = yield call(addUser, payload);
      if (response.status === 'success') {
        message.success('添加成功');
        router.push('/userlist/table-list');
      } else {
        message.error('添加失败');
      }
    },

    *handle({ payload }, { call, put }) {
      const response = yield call(handleAccount, payload);
      if (response.code === 200) {
        const res = yield call(queryUsersList, payload);

        yield put({
          type: 'save',
          payload: {
            list: res.data.data,
            pagination: {
              total: res.data.total,
              pageSize: 10,
              current: parseInt(res.data.currentPage, 10) || 1,
            },
          },
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        userMap: action.payload,
      };
    },
    saveUserinfo(state, action) {
      return {
        ...state,
        userInfo: action.payload,
      };
    },
  },
};
